package com.mls.wms.android.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.http.RequestManager;
import com.mls.wms.android.R;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.model.GlobalSetting;
import com.mls.wms.android.model.ResponseResult;
import com.mls.wms.android.util.DialogUtils;
import com.mls.wms.android.util.UpdateManager;

import java.util.HashMap;
import java.util.Map;


public class LoginActivity extends BaseActivity {
    private TextView login_lbl_server_ip;
    private TextView login_lbl_tenant_no;
    private TextView login_lbl_warehouse_no;
    private TextView login_lbl_login_name;
    private TextView login_lbl_pwd;

    private EditText mServerIPView;
    private EditText mTenantNoView;
    private EditText mWarehouseNoView;
    private EditText mLoginNameView;
    private EditText mPasswordView;

    private Button mBtnSignIn;
    private AnimDialogFragment progressDialog = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_login);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        login_lbl_server_ip = (TextView) findViewById(R.id.login_lbl_server_ip);
        login_lbl_tenant_no = (TextView) findViewById(R.id.login_lbl_tenant_no);
        login_lbl_warehouse_no = (TextView) findViewById(R.id.login_lbl_warehouse_no);
        login_lbl_login_name = (TextView) findViewById(R.id.login_lbl_login_name);
        login_lbl_pwd = (TextView) findViewById(R.id.login_lbl_pwd);

        login_lbl_tenant_no.setTypeface(_BaseApplication.getIconFont());
        login_lbl_server_ip.setTypeface(_BaseApplication.getIconFont());
        login_lbl_warehouse_no.setTypeface(_BaseApplication.getIconFont());
        login_lbl_login_name.setTypeface(_BaseApplication.getIconFont());
        login_lbl_pwd.setTypeface(_BaseApplication.getIconFont());

        mServerIPView = (EditText) findViewById(R.id.txtServerIP);
        mTenantNoView = (EditText) findViewById(R.id.txtTenantNo);
        mWarehouseNoView = (EditText) findViewById(R.id.txtWarehouseNo);
        mLoginNameView = (EditText) findViewById(R.id.txtLoginName);
        mPasswordView = (EditText) findViewById(R.id.txtPassword);

        mBtnSignIn = (Button) findViewById(R.id.act_login_btn_sign_in);


        //缓存数据
        SharedPreferences sp = getSharedPreferences("setting", Context.MODE_PRIVATE);
        String serverIP = sp.getString("ServerIP", "http://wms.meilishuo.com");
        String tenantNo = sp.getString("TenantNo", "meilishuo");
        String warehouseNo = sp.getString("WarehouseNo", "SH1");
        String loginName = sp.getString("LoginName", "0106");

        _BaseApplication.getGlobalSetting().setServerIP(serverIP);

        mServerIPView.setText(serverIP);
        mTenantNoView.setText(tenantNo);
        mWarehouseNoView.setText(warehouseNo);
        mLoginNameView.setText(loginName);

        mBtnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptLogin(false);
            }
        });

        UpdateManager updateManager = new UpdateManager(this, progressDialog);
        updateManager.checkUpdate();
    }

    /**
     * 登录
     */
    public void attemptLogin(Boolean force) {
        // Reset errors.
        mServerIPView.setError(null);
        mWarehouseNoView.setError(null);
        mLoginNameView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String serverIP = mServerIPView.getText().toString();
        String tenantNo = mTenantNoView.getText().toString();
        String warehouseNo = mWarehouseNoView.getText().toString();
        String loginName = mLoginNameView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        //服务IP
        if (TextUtils.isEmpty(serverIP)) {
            mServerIPView.setError(getString(R.string.error_field_required));
            focusView = mServerIPView;
            cancel = true;
        }
        _BaseApplication.getGlobalSetting().setServerIP(serverIP);
        //租户编码
        if (TextUtils.isEmpty(tenantNo)) {
            mTenantNoView.setError(getString(R.string.error_field_required));
            focusView = mTenantNoView;
            cancel = true;
        }
        _BaseApplication.getGlobalSetting().setTenantNo(tenantNo);
        //仓库编码
        if (TextUtils.isEmpty(warehouseNo)) {
            mWarehouseNoView.setError(getString(R.string.error_field_required));
            focusView = mWarehouseNoView;
            cancel = true;
        }
        // 登录名校验
        if (TextUtils.isEmpty(loginName)) {
            mLoginNameView.setError(getString(R.string.error_field_required));
            focusView = mLoginNameView;
            cancel = true;
        }
        // 密码校验
        if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }


        if (cancel) {
            focusView.requestFocus();
        } else {
            if (false == progressDialog.isVisible()) {
                progressDialog.show(getFragmentManager(), this.toString());
            }

            Map<String, String> map = new HashMap<String, String>();
            map.put("uname", loginName);
            map.put("pwd", password);
            map.put("tenantNo", tenantNo);
            map.put("warehouseNo", warehouseNo);
            map.put("isForceLogin", force.toString());

            get(ServicePort.getUrl(ServicePort.Login), map, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            GlobalSetting setting = new GlobalSetting();
                            setting = setting.parseJson(result.getResult().toString());

                            _BaseApplication.getGlobalSetting().setToken(setting.getToken());
                            _BaseApplication.getGlobalSetting().setModuleService(setting.getModuleService());
                            _BaseApplication.getGlobalSetting().setIsMultiScan(setting.getIsMultiScan());

                            _BaseApplication.getGlobalSetting().setTenantId(setting.getTenantId());
                            _BaseApplication.getGlobalSetting().setTenantNo(setting.getTenantNo());

                            _BaseApplication.getGlobalSetting().setWarehouseId(setting.getWarehouseId());
                            _BaseApplication.getGlobalSetting().setWarehouseNo(setting.getWarehouseNo());
                            _BaseApplication.getGlobalSetting().setWarehouseName(setting.getWarehouseName());

                            _BaseApplication.getGlobalSetting().setUserId(setting.getUserId());
                            _BaseApplication.getGlobalSetting().setLoginName(setting.getLoginName());
                            _BaseApplication.getGlobalSetting().setUserName(setting.getUserName());


                            //保存缓存
                            SharedPreferences sp = getSharedPreferences("setting", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sp.edit();

                            editor.putString("ServerIP", mServerIPView.getText().toString());
                            editor.putString("TenantNo", setting.getTenantNo());
                            editor.putLong("WarehouseId", setting.getWarehouseId());
                            editor.putString("WarehouseNo", mWarehouseNoView.getText().toString());
                            editor.putString("WarehouseName", setting.getWarehouseName());

                            editor.putLong("UserId", setting.getUserId());
                            editor.putString("LoginName", mLoginNameView.getText().toString());
                            editor.putString("UserName", setting.getUserName());

                            editor.putInt("IsMultiScan", setting.getIsMultiScan());
                            editor.putString("Token", setting.getToken());
                            editor.apply();

                            progressDialog.dismiss();

                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setClass(LoginActivity.this, MainActivity.class);
                            LoginActivity.this.startActivity(intent);
                            LoginActivity.this.finish();
                            return;
                        } else {
                            if ("E00141".equals(result.getCode())) {
                                final String message = result == null ? "是否强制登录?" : result.getMessage();
                                DialogUtils.showYesNo(LoginActivity.this, getResources().getString(R.string.title_text_tip), message,
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                attemptLogin(true);
                                            }
                                        }, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                progressDialog.dismiss();
                                            }
                                        });

                            } else {
                                errorMsg = result.getMessage();
                            }
                        }
                    } catch (Exception e) {
                        errorMsg = e.getMessage();
                        e.printStackTrace();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        progressDialog.dismiss();
                        showError(errorMsg);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    progressDialog.dismiss();
                    showError(s);
                }
            }, 1);
        }
    }

    private void showError(String errorMsg) {
        if (TextUtils.isEmpty(errorMsg)) {
            mPasswordView.setError(getString(R.string.error_incorrect_password));
        } else {
            mPasswordView.setError(errorMsg);
        }
        mPasswordView.requestFocus();
    }

    private boolean isPasswordValid(String password) {
        return password.length() > 2;
    }


}



